import Tosat from "./toastMask.vue";

let ToastConstructor, Vue;

/**
 * 关闭
 */
function onAnimEnd() {
    let node = this.$el;
    if (node) {
        node.parentNode.removeChild(node);
    }

    // 销毁实例
    setTimeout(() => {
        this.$destroy();
    }, 10);
}

export let option = {};

/**
 * 显示 toast
 * @param {Object} options
 */
function toast(options = {}) {
    let opt = Object.assign({}, option, typeof options == "string" ? { message: options } : options);
    // 延时关闭toast
    let duration = opt.duration || 3000;
    var toast = new ToastConstructor({
        el: document.createElement("div")
    });

    Object.assign(toast, opt);

    // toast.$on("close", onClose);
    toast.$on("animEnd", onAnimEnd);

    document.body.appendChild(toast.$el);

    Vue.nextTick(function() {
        toast.visible = 1;
        if (~duration) {
            setTimeout(function() {
                toast.close(0);
            }, duration);
        }
    });
    return toast;
}

/**
 * 全局插件形式注册组件
 * @param {Vue} vue
 * @param {String} toastName
 */
export default function install(vue, toastName) {
    if (Vue) {
        return;
    }
    Vue = vue;
    ToastConstructor = vue.extend(Tosat);

    vue.prototype["$" + toastName] = toast;
}
